

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:toast/toast.dart';

class MyApp extends StatelessWidget{
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
       DateTime? _lastPressedAt; //上次点击时间
      return MaterialApp(
        title: "Flutter Demo",
        initialRoute:"/", //名为"/"的路由作为应用的home(首页)
        onGenerateRoute:(RouteSettings settings){
          return MaterialPageRoute(builder: (context){
            String? routeName = settings.name;
            // 如果访问的路由页需要登录，但当前未登录，则直接返回登录页路由，
            // 引导用户登录；其它情况则正常打开路由。
              return Text("测试");

          }
          );
        },
        routes: {
          "new_page":(context) => NewRoute(),
        } ,
        theme: ThemeData(primaryColor: Colors.blue),
        home:  WillPopScope(child: MyHomePage(), onWillPop: () async  {
          if (_lastPressedAt == null ||
              DateTime.now().difference(_lastPressedAt!) > const Duration(seconds: 1)) {
            //两次点击间隔超过1秒则重新计时
            _lastPressedAt = DateTime.now();
            return false;
          }
          return true;
        }),
      );
  }
}

class MyHomePage extends StatefulWidget{
  const MyHomePage({Key? key}) : super(key: key);


  @override
  State<StatefulWidget> createState() => _MyHomePageState();
}

class _MyHomePageState extends State{
  int _counter = 0;

  @override
  Widget build(BuildContext context) {

       return Scaffold(
         appBar: AppBar(title: const Text("'Flutter Demo Home Page'"),),
         body: Center(
           child: Column(
             mainAxisAlignment: MainAxisAlignment.center,
             children: <Widget>[
               const Text('You have pushed the button this many times:'),
               Text(
                 '$_counter',
                 style: Theme.of(context).textTheme.headline4,
               ),
               TextButton(
                   onPressed: ()  {
//导航到新路由
//                      Navigator.push(
//                        context,
//                        MaterialPageRoute(builder: (context) =>NewRoute()),
//                      );
                     Navigator.pushNamed(context, "new_page");

                   },
                 child: const Text("open new route"),)
             ],
           ),
         ),
         floatingActionButton: FloatingActionButton(
           onPressed: _incrementCounter,
           tooltip: 'Increment',
           child: const Icon(Icons.add),
         ), // This trailing comma makes auto-formatting nicer for build methods.,
       );
  }

  void _incrementCounter(){
     setState(() {
         _counter++;
     });
  }
}


class NewRoute extends StatelessWidget {
  const NewRoute({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("New route"),
      ),
      body: const Center(
        child: Text("This is new route"),
      ),
    );
  }
}




//测试state的生命周期

 class CounterWidget extends StatefulWidget {

   final int initValue;

   const CounterWidget({Key? key, this.initValue = 0});


   @override
   _CounterWidgetState createState() => _CounterWidgetState();
 }


 class _CounterWidgetState extends State<CounterWidget>{

   int _counter = 0;

   @override
   void initState() {
     super.initState();
     //初始化状态
     _counter = widget.initValue;
     print("initState");
   }

     @override
   Widget build(BuildContext context) {
     print("build");
     return Scaffold(
       body: Center(
         child: TextButton(
           child: Text('$_counter'),
           //点击后计数器自增
           onPressed: () => setState(
                 () => ++_counter,
           ),
         ),
       ),
     );
   }

   @override
   void didUpdateWidget(CounterWidget oldWidget) {
     super.didUpdateWidget(oldWidget);
     print("didUpdateWidget ");
   }

   @override
   void deactivate() {
     super.deactivate();
     print("deactivate");
   }

   @override
   void dispose() {
     super.dispose();
     print("dispose");
   }

   @override
   void reassemble() {
     super.reassemble();
     print("reassemble");
   }

   @override
   void didChangeDependencies() {
     super.didChangeDependencies();
     print("didChangeDependencies");
   }
 }


class StateLifecycleTest extends StatelessWidget {
  const StateLifecycleTest({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return CounterWidget();
  }
}



class GetStateObjectRoute extends StatefulWidget {
  const GetStateObjectRoute({Key? key}) : super(key: key);


  @override
  State<GetStateObjectRoute> createState() => _GetStateObjectRouteState();
}

class _GetStateObjectRouteState extends State<GetStateObjectRoute> {


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("子树中获取State对象"),
      ),
      body: Center(
        child: Column(
          children: [
            Builder(builder: (context) {
              return Column(children: [
                ElevatedButton(
                  onPressed: () {
                // 查找父级最近的Scaffold对应的ScaffoldState对象
                ScaffoldState _state = context.findAncestorStateOfType<ScaffoldState>()!;
                _state.openDrawer();
              },
              child: Text('打开抽屉菜单1'),
              ),
                ElevatedButton(
                  onPressed: () {
                    ScaffoldState _state = Scaffold.of(context);
                    _state.openDrawer();

              },
              child: Text('打开抽屉菜单2'),
              )

              ],);
            }),
          ],
        ),
      ),
      drawer: Drawer(),
    );
  }
}

//ios风格
class CupertinoTestRoute extends StatelessWidget  {
  const CupertinoTestRoute({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return CupertinoPageScaffold(
      navigationBar: const CupertinoNavigationBar(
        middle: Text("Cupertino Demo"),
      ),
      child: Center(
        child: CupertinoButton(
            color: CupertinoColors.activeBlue,
            child: Text("Press"),
            onPressed: () {}
        ),
      ),
    );
  }
}


